//从axios框架导入axios组件
import axios from "axios";
import {getTokenName, messageConfirm, messageTip, removeToken} from "../util/util.js";
import {ElMessage, ElMessageBox} from "element-plus";

// 创建 axios 实例，并设置不同的 baseURL
const axiosInstance = axios.create({
    baseURL: "http://localhost:8090"  // 文件1的接口前缀
});

const contentService = {
    doGet(url, params) {
        return axiosInstance({
            method: "get",
            url: url,
            params: params,
        });
    },
    doPost(url, data) {
        return axiosInstance({
            method: "post",
            url: url,
            data: data,
        });
    },
    doPut(url, data) {
        return axiosInstance({
            method: "put",
            url: url,
            data: data,
        });
    },
    doDelete(url) {
        return axiosInstance({
            method: "delete",
            url: url,
        });
    },
    setupInterceptors() {
        axiosInstance.interceptors.request.use(
            (config) => {
                let token = window.sessionStorage.getItem(getTokenName());
                if (!token) {
                    token = window.localStorage.getItem(getTokenName());
                }
                if (token) {
                    config.headers['Authorization'] = token;
                }
                return config;
            },
            (error) => {
                return Promise.reject(error);
            }
        );

        axiosInstance.interceptors.response.use(
            (response) => {
                if (response.data.code > 900) {
                    messageConfirm(response.data.msg + "，是否重新去登录？").then(() => {
                        removeToken();
                        window.location.href = "/";
                    }).catch(() => {
                        messageTip("取消去登录", "warning");
                    });
                    return Promise.reject(new Error("Token validation failed"));
                }
                return response;
            },
            (error) => {
                return Promise.reject(error);
            }
        );
    }
};

// 默认导出 apiService 对象
export default contentService;
